package com.zhongshengnetwork.rightbe.https;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

import android.os.Handler;
import android.os.Looper;

/**
 * Created by GordonLjx on 2016/9/21.
 */
public class OkHttpUtils {
    //json请求
    public static final MediaType JSON = MediaType
            .parse("application/json; charset=utf-8");
    private static Handler handler = new Handler(Looper.getMainLooper());

    private static void onSuccess(final HttpCallBack callback, final String data) {
        if (null != callback) {
            handler.post(new Runnable() {
                public void run() {
                    // 需要在主线程的操作。
                    System.out.print("需要在主线程的操作\n");
                    callback.onSuccess(data);
                }
            });
        }
    }

    private static void onError(final HttpCallBack callback,final String msg) {
        if (null != callback) {
            handler.post(new Runnable() {
                public void run() {
                    // 需要在主线程的操作。
                    callback.onError(msg);
                }
            });
        }
    }

    //okhttp调试
    public static void postJson(String url, String json, final HttpCallBack callback) {

        RequestBody body = RequestBody.create(JSON, json);

//        Request request = new Request.Builder().url(url).post(body).build();
//
//        CustomApplication.okHttpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//
//            }
//
//            @Override
//            public void onResponse(Call call, okhttp3.Response response) throws IOException {
//
//            }
//        });

    }

    public static void postLoginJson(String json, final HttpCallBack callback){
//        String url = Constant.HOST + ApiUtils.loginApi;
//        RequestBody body = RequestBody.create(JSON, json);
//        System.out.print("json="+json+"\n");
//        System.out.print("body="+body.toString()+"\n");
//        Request request = new Request.Builder().url(url).post(body).build();
//
//        CustomApplication.okHttpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                onError(callback,e.getMessage());
//            }
//
//            @Override
//            public void onResponse(Call call, okhttp3.Response response) throws IOException {
//                if (response.isSuccessful()){
//                    onSuccess(callback,response.body().string());
//                }else {
//                    onError(callback,response.message());
//                }
//            }
//        });
    }
}
